﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Xml.Serialization;
using System.Windows.Forms;
using System.Data;
using System.Reflection;
using System.Drawing;

namespace DotNet.Utilities.Entity帮助类
{
    public static class EntityHelper
    {
        #region 实体转字符串
        /// <summary>
        /// 实体转字符串
        /// </summary>
        /// <typeparam name="T">类型</typeparam>
        /// <param name="entity">实体实例</param>
        /// <returns>转换后的字符串</returns>
        public static string EntityToString<T>(T entity)
        {
            string result = string.Empty;
            try
            {
                using (MemoryStream ms = new MemoryStream())
                {
                    XmlSerializer ser = new XmlSerializer(typeof(T));
                    ser.Serialize(ms, entity);
                    result = Convert.ToBase64String(ms.ToArray());
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }
            return result;
        }
        #endregion

        #region 字符串转实体
        /// <summary>
        /// 字符串转实体
        /// </summary>
        /// <typeparam name="T">类型</typeparam>
        /// <param name="entityString">字符串</param>
        /// <returns></returns>
        public static T StringToEntity<T>(string entityString) where T : new()
        {
            T entity = new T();
            try
            {
                byte[] buffer = Convert.FromBase64String(entityString);
                using (System.IO.MemoryStream ms = new System.IO.MemoryStream(buffer))
                {
                    System.Xml.Serialization.XmlSerializer ser = new System.Xml.Serialization.XmlSerializer(typeof(T));
                    entity = (T)ser.Deserialize(ms);
                }
            }
            catch (Exception ex)
            {
                //throw ex;
            }
            return entity;
        }
        #endregion

        #region 绑定ListView
        /// <summary>
        /// 绑定ListView
        /// </summary>
        /// <typeparam name="T">类型</typeparam>
        /// <param name="listView">ListView实例</param>
        /// <param name="list">结果集合</param>
        public static void SetListView<T>(ListView listView, List<T> list) where T : class, new()
        {
            T entity = new T();

            listView.Items.Clear();
            listView.Columns.Clear();

            listView.View = View.Details;
            listView.FullRowSelect = true;

            ImageList imgList = new ImageList();
            imgList.ImageSize = new Size(1, 20);

            listView.SmallImageList = imgList;


            //========================设置表头栏位===========================
            var propertyList = entity.GetType().GetProperties();

            foreach (var propInfo in propertyList)
            {
                object[] colAttrs = propInfo.GetCustomAttributes(typeof(TableColumnAttribute), true);
                if (colAttrs.Length > 0)
                {
                    TableColumnAttribute attr = colAttrs[0] as TableColumnAttribute;
                    DataGridTextBoxColumn col = new DataGridTextBoxColumn();
                    listView.Columns.Add(new ColumnHeader { Text = attr.ColumnName, Width = attr.Width });
                }
            }

            //添加数据
            foreach (var model in list)
            {
                string[] itemStr = new string[propertyList.Length];
                for (int i = 0; i < propertyList.Length; i++)
                {
                    object[] colAttrs = propertyList[i].GetCustomAttributes(typeof(TableColumnAttribute), true);
                    if (colAttrs.Length > 0)
                    {
                        TableColumnAttribute attr = colAttrs[0] as TableColumnAttribute;
                        itemStr[i] = propertyList[i].GetValue(model, null).ToString();

                        //string valueStr = propertyList[i].GetValue(model, null).ToString();
                        //if (valueStr.ToUpper() == "TRUE")
                        //{
                        //    itemStr[i] = "是";
                        //}
                        //else if (valueStr.ToUpper() == "FALSE")
                        //{
                        //    itemStr[i] = "否";
                        //}
                        //else
                        //{
                        //    itemStr[i] = valueStr;
                        //}
                    }
                }
                listView.Items.Add(new ListViewItem(itemStr));
            }
        }
        #endregion

        #region 绑定DataGrid
        public static void SetDataGrid<T>(DataGrid grid, List<T> list) where T : class, new()
        {
            T entity = new T();

            //========================绑定数据===========================
            DataTable table = new DataTable();
            string tableName = entity.GetType().Name + "Table";
            table.TableName = tableName;

            foreach (var propInfo in entity.GetType().GetProperties())
            {
                table.Columns.Add(new DataColumn { ColumnName = propInfo.Name });
            }

            foreach (var m in list)
            {
                DataRow row = table.NewRow();
                foreach (var propInfo in m.GetType().GetProperties())
                {
                    row[propInfo.Name] = propInfo.GetValue(m, null);
                }
                table.Rows.Add(row);
            }
            //========================绑定数据===========================

            grid.DataSource = table;

            //========================设置表头栏位========================
            grid.TableStyles.Clear();
            DataGridTableStyle dts = new DataGridTableStyle();
            dts.MappingName = tableName;

            foreach (var propInfo in entity.GetType().GetProperties())
            {
                object[] colAttrs = propInfo.GetCustomAttributes(typeof(TableColumnAttribute), true);
                if (colAttrs.Length > 0)
                {
                    TableColumnAttribute attr = colAttrs[0] as TableColumnAttribute;
                    DataGridTextBoxColumn col = new DataGridTextBoxColumn();
                    col.Width = attr.Width;
                    col.HeaderText = attr.ColumnName;
                    col.MappingName = attr.FieldName;
                    dts.GridColumnStyles.Add(col);
                }
            }
            grid.TableStyles.Add(dts);
            //========================设置表头栏位=========================
        }
        #endregion

        #region 返回枚举列表
        public static List<string> GetEnumList<T>()
        {
            List<string> result = new List<string>();

            // 创建类型
            Type enumType = typeof(T);
            // 创建类型
            FieldInfo[] enumFields = enumType.GetFields();
            // 遍历集合
            foreach (FieldInfo field in enumFields)
            {
                if (!field.IsSpecialName)
                {
                    result.Add(field.Name);
                }
            }

            return result;
        }
        #endregion


    }
}
